import { CustomForm } from "@/components/ProForm/interface";
import dayjs from "dayjs";

export const useForm = () => {
  const addForm = reactive<CustomForm>({
    save: () => null,
    form: {
      price: "",
      amount: "",
      date: "",
      remark: "",
      type: "",
      type2: "",
      userId: ""
    },
    options: [
      {
        hide: false,
        label: "基础信息",
        type: "title"
      },
      {
        type: "date_custom",
        hide: false,
        label: "日期",
        prop: "date",
        defaultValue: dayjs().format("YYYY-MM-DD"),
        children: [],
        attrs: {
          type: "date"
        },
        rules: [
          {
            required: true,
            errorMessage: "日期"
          }
        ]
      },
      {
        type: "select",
        hide: false,
        label: "购买用户",
        prop: "userId",
        children: [],
        changeMethod: form => {
          form.quantity = "";
        },
        rules: [
          {
            required: true,
            errorMessage: "购买用户"
          }
        ]
      },
      {
        type: "select",
        hide: false,
        label: "交易情况",
        prop: "type2",
        defaultValue: 1,
        children: [],
        rules: [
          {
            required: true,
            errorMessage: "交易情况"
          }
        ]
      },

      {
        type: "input",
        label: "股票代码",
        hide: false,
        prop: "dms",
        attrs: {
          disabled: false,
          maxlength: -1
        }
      },
      {
        type: "input",
        label: "备注",
        hide: false,
        prop: "remark",
        attrs: {
          disabled: false
        }
      }
    ]
  });

  let userInfo = {
    money: 0,
    id: 0,
    userOp: [],
    // 持仓列表
    positionsOp: []
  };

  /**
   * @description: 获取所有用户
   * @return {*}
   */
  const getAllUser = async () => {
    const data: any = await userFindAllUser();
    userInfo.userOp = data;

    for (let item of addForm.options) {
      if (item.prop === "userId") {
        item.children = data.map(item => {
          return {
            text: item.userName,
            value: item.id
          };
        });
      }
    }
  };

  const submitForm = async form => {
    const params = { ...form };
    // 使用正则表达式替换多余的空格为一个空格
    const str = params.dms.replace(/\s+/g, " ");
    // 按空格分割字符串为数组
    params.dms = str.split(" ");
    params.type = "buy";
    await transactionsAddTransactionsList(params);
    useGlobalStore().setMessage();
    clearForm();
  };

  const clearForm = () => {
    Object.keys(addForm.form).forEach(key => {
      if (key !== "date") {
        addForm.form[key] = "";
      }
    });

    // 重新获取用户得到新的金额
    getAllUser();
  };

  return {
    addForm,
    submitForm,
    getAllUser
  };
};
